package com.demo.youxuanmall.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Order;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.service.OrderService;
import com.demo.youxuanmall.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminOrderController {

    @Autowired
    private OrderService orderService;
    private final UserService userService;
    private final SpringTemplateEngine templateEngine;
    
    public AdminOrderController(UserService userService, SpringTemplateEngine templateEngine) {
        this.userService = userService;
        this.templateEngine = templateEngine;
    }

    @GetMapping("/orders")
    public String ordersPage(Model model, HttpSession session) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return "redirect:/403";
        }
        
        try {
            // 查询订单统计
            Result<Integer[]> statsResult = orderService.getOrderStats();
            if (statsResult.getCode() == 0 && statsResult.getData() != null) {
                model.addAttribute("orderStats", statsResult.getData());
            }
            return "admin/orders";
        } catch (Exception e) {
            log.error("加载订单管理页面出错", e);
            model.addAttribute("error", "加载失败，请稍后再试");
            return "admin/orders";
        }
    }
    
    @GetMapping("/api/orders")
    @ResponseBody
    public Result<Page<Order>> getOrdersAjax(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限访问");
        }
        
        try {
            // 根据是否有搜索关键词或状态筛选，执行不同的查询
            Result<Page<Order>> result;
            if (keyword != null && !keyword.trim().isEmpty()) {
                // 搜索订单
                result = orderService.searchOrders(keyword, status, pageNum, pageSize);
            } else if (status != null) {
                // 按状态查询
                result = orderService.listAllOrdersByStatus(status, pageNum, pageSize);
            } else {
                // 查询所有订单
                result = orderService.listAllOrders(pageNum, pageSize);
            }
            
            return result;
        } catch (Exception e) {
            log.error("加载订单列表出错", e);
            return Result.error("加载失败，请稍后再试");
        }
    }
    
    /**
     * 查看订单详情
     */
    @GetMapping("/orders/detail/{orderNo}")
    public String orderDetail(@PathVariable String orderNo, Model model, HttpSession session) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return "redirect:/403";
        }
        
        try {
            // 查询订单详情
            Result<Order> result = orderService.getOrderDetail(null, orderNo);
            if (result.getCode() == 0 && result.getData() != null) {
                model.addAttribute("order", result.getData());
            } else {
                model.addAttribute("error", result.getMsg());
            }
            
            return "admin/order-detail";
        } catch (Exception e) {
            log.error("加载订单详情页面出错: {}", orderNo, e);
            model.addAttribute("error", "加载失败，请稍后再试");
            return "admin/order-detail";
        }
    }
    
    /**
     * 发货处理
     */
    @PostMapping("/order/ship")
    @ResponseBody
    public Result<Void> shipOrder(@RequestParam String orderNo, HttpSession session) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        try {
            log.info("管理员发货: orderNo={}", orderNo);
            return orderService.shipOrder(orderNo);
        } catch (Exception e) {
            log.error("发货处理异常: {}", orderNo, e);
            return Result.error("发货失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/order/cancel")
    @ResponseBody
    public Result<Void> cancelOrder(@RequestParam String orderNo, HttpSession session) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return Result.error("无权限操作");
        }
        
        try {
            log.info("管理员取消订单: orderNo={}", orderNo);
            // 管理员取消订单时传入null作为userId，表示管理员操作
            return orderService.cancelOrder(null, orderNo);
        } catch (Exception e) {
            log.error("取消订单异常: {}", orderNo, e);
            return Result.error("取消订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 按状态查询订单
     */
    @GetMapping("/orders/status/{status}")
    public String getOrdersByStatus(
            @PathVariable Integer status, 
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            Model model,
            HttpSession session
    ) {
        // 验证管理员权限
        User user = (User) session.getAttribute("user");
        if (user == null || user.getRole() != 1) {
            return "redirect:/403";
        }
        
        try {
            // 查询订单统计 - 始终获取全部订单统计数据
            Result<Integer[]> statsResult = orderService.getOrderStats();
            if (statsResult.getCode() == 0 && statsResult.getData() != null) {
                model.addAttribute("orderStats", statsResult.getData());
            }
            
            // 查询订单列表
            Result<Page<Order>> result = orderService.listAllOrdersByStatus(status, pageNum, pageSize);
            if (result.getCode() == 0 && result.getData() != null) {
                model.addAttribute("orderPage", result.getData());
                model.addAttribute("status", status);
            } else {
                model.addAttribute("error", result.getMsg());
            }
            
            return "admin/orders";
        } catch (Exception e) {
            log.error("按状态查询订单出错: status={}", status, e);
            model.addAttribute("error", "查询失败，请稍后再试");
            return "admin/orders";
        }
    }
} 